package com.zh.flowable.web;

import com.zh.mycommon.util.MyCommonUtil;
import com.zh.flowable.domain.user.LoginRequest;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
import java.util.concurrent.CompletableFuture;

/**
 * @author
 * @date 2025/8/18
 */
@Slf4j
@RestController
@RequestMapping("/api")
public class HelloController {

    @GetMapping("/hello")
    public String hello() {
        CompletableFuture.runAsync(() -> {
            System.out.println("异步任务执行start...");

        });
        return "hello";
    }


    /**
     * 登录接口
     * 登录成功后，返回token，并写入cookie
     */
    @PostMapping("/auth/login")
    public Map<String, String> login(@RequestBody LoginRequest loginReq
            , HttpServletResponse response) {
        System.out.println("call login...");

        //模拟的用户登录
        var username = loginReq.getUsername();
        var userId = loginReq.getUsername().hashCode();
        var roles = "ROLE_ADMIN,ROLE_MANAGER";

        var token = MyCommonUtil.base64Encode(String.format("%d;%s;%s", userId, username, roles));
        System.out.println("generate token: " + token);

        //写入cookie
        Cookie cookie = new Cookie("token", token);
        cookie.setHttpOnly(true);
        cookie.setSecure(false);
        cookie.setPath("/");
        response.addCookie(cookie);

        System.out.println("write cookie: " + token + " path: " + cookie.getPath());

        return Map.of("access_token", token);
    }

}
